(function($){
	function formResult(msg, state) {
        layer.closeAll();
        if(state == 0) {
            layer.alert(msg, {icon: 5});
        }
    }
	$(function () {
		//获得当前的的日期
		function getNewDate() {
			var NewDate = laydate.now(0, 'YYYY/MM/DD hh:mm:ss')
			return (NewDate);
		}

		$(function () {
				$("#ordertime").val(getNewDate);
		})
	})


	/**
	 * 会员会员
	 * @param id
	 */
	function select_user(id){
		var url='/business/financial/cashier?action=getuserinfo';
		$.ajax({
			type:'POST',
			dataType:'json',
			url:url,
			data:{id:id},
			success:function (data){
				if(data.state==0){
					 layer.alert(data.message, {icon: 5});
				}else{
					displayUserinfo(data.result);
					parent.$('body').addClass('msgTips');
					parent.$('.guide-con-tip').html('亲,点这里<br>添加卡项信息哦');
				}
			}
		})
	}
	/**
	 * 显示会员信息
	 */
	function displayUserinfo(data){
		$('.table tbody').empty();
		$('.clearingBtn').addClass('hide');
		layer.closeAll();
		str = '<p>'+data.member_name+'&nbsp;&nbsp;|&nbsp;&nbsp;'+defaultMemberVal(data.member_mobile)+'&nbsp;&nbsp;|&nbsp;&nbsp;'+defaultMemberVal(data.member_grade)+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;储值卡：<em>'+defaultMemberVal(data.member_balance,0)+'</em>&nbsp;&nbsp;|&nbsp;&nbsp;欠款:&nbsp;&nbsp;<em>'+defaultMemberVal(data.member_debt,0)+'</em>&nbsp;&nbsp;|&nbsp;&nbsp;赠送剩余：<em>'+defaultMemberVal(data.member_give_balance,0)+'</em></p>';
		str +='<span class="btnMd btn-success add" id="add" onclick="getUserlist('+"'会员列表'"+','+"'/business/financial/cashier?action=getUserlist'"+')" style="background-color:#fe7b9d;border-color:#fe7b9d;cursor:pointer;width: 82px;position: absolute;right: 0;top: 0;">更改会员</span>';
		$(".user").html(str);
		addInput('member_id',data.member_id);

		var durl = $(".clearingBtn").attr('durl');
		var url = durl+"&member_id="+data.member_id;
		$(".clearingBtn").attr('durl',url);
		$('.dLabel').removeAttr('disabled');
		$('.dLabel').parent().removeClass('btn_disabled');

		//选择会员刷新
		$.ajax({
			type:'POST',
			dataType:'json',
			url:'/business/financial/cashier?action=productlist',
			data:{member_id:data.member_id},
			success:function (data){

				if(data.state==1){
					var html = '';
					function trans(data) {
						var $type;
						switch (data) {
							case '1':
								$type = '储值卡';
								break;
							case '2':
								$type = '疗程卡';
								break;
							case '3':
								$type = '家居产品';
								break;
							case '4':
								$type = '合作项目';
								break;
							case '5':
								$type = '服务项目';
								break;
						}
						return $type;
					}

					var arrSum = [];
					parent.$('.table tbody').empty();
					$.each(data.result,function(i,o){
						arrSum.push(o.really_price * o.count);
						html = '<tr>' +
							'<form>' +
							'<td>'+ trans(o.finance_type)+'</td>' +
							'<td>'+ o.consume_name+'</td>' +
							'<td>'+ o.sell_price+'</td>' +
							'<td><input class="calc reaPrice" type="text" value="'+o.really_price+'"/></td>' +
							'<td><input class="calc count" type="text" value="'+ o.count +'"></td>' +
							'<td>'+ o.really_price * o.count+'</td>' +
							'<td><a data-nid="'+i+'" class="add-member btn btn-sm" href="javascript:;" onclick="openP('+"'/business/financial/cashier?action=stafflist'"+','+ i +','+ o.finance_id+')">'+defaultVal(o.employee_name)+'</a></td>' +
							'<td><input class="saleFeat" type="text" value="'+ defaultReward(o.reward) +'"></td>' +
							'<td><input class="but_set_state btn btn-sm btn-borB" type="submit" value="删除" durl="/business/financial/cashier?action=delproduct" did="'+ o.finance_id+'" mid="'+ o.member_id+'"/></td>' +
							'</form>'+
							'</tr>';


						parent.$('.table tbody').append(html);

					});
					var allMoney = arrSum.reduce(function (x,y) {
						return x + y;
					});
					parent.$('.table tbody').append('<tr style="border: none">' +
						'<td colspan="1" style="border-right: 0;">总计金额：' +
						'<em class="red">￥<span class="total-money">'+allMoney+'</span></em>' +
						'</td>' +
						'<td class="text-right" colspan="8" style="border-left: 0;">' +
						'<em class="red">提示：</em>' +
						'会员有多次服务消费的情况，请选择疗程卡；会员单次项目服务消费的情况，请选择有服务项目会员消费后，无需提供后续服务，请选择无服务项目' +
						'</td>' +
						'</tr>');
					parent.$('.table').parent().find('.clearingBtn').removeClass('hide');

					parent.layer.closeAll();

				}else{
					layer.alert(data.message, {icon: 5});
				}
			}
		})
	}
	/**
	 * 设置提成人员默认值
	 */
	function defaultVal(param,val){
		if(val==null || val=='' || param==undefined){
			val = '<img src="/backend/img/financial/addpeople.png">';
		}
		if(param==null || param=='' || param==undefined){
			return val;
		}else{
			return param;
		}
	}
	/**
	 * 设置会员信息默认值
	 */
	function defaultMemberVal(param,val){
		if(val==null || val=='' || param==undefined){
			val = '无';
		}
		if(param==null || param=='' || param==undefined){
			return val;
		}else{
			return param;
		}
	}
	function defaultReward(data) {
		if(data == null) {
			return ''
		} else {
			return data;
		}
	}
	/**
	 * 获取会员列表
	 */
	function getUserlist(title,url){
		layer.open({
		    type: 2,
		    area: ['1000px', '640px'],
		    title:title,
		    fix: true, //不固定
		    maxmin: true,
		    content: url
		});
	}
	/**
	 * 添加隐藏域
	 */
	function addInput(name,val){
		$member_id = val;
		str = '<input class="member_id" type="text" name="'+name+'" value="'+val+'">';
		$(".inputParam").append(str);
	}
	/**
	 * 关闭layer的窗口
	 */
	function closeWindow(){
		layer.closeAll();
	}

	/**
	 * 添加充值卡获取member_id
	 */
	var $member_id;
	function getMember_id() {
		return $member_id;
	}


	/**
	 * 添加提成人员
	 * @param url
	 */
	var $nid;
	function getNid() {
		return $nid;
	}
	var $fid;
	function getFid() {
		return $fid;
	}
	function openP(url,nid,fid){
		$nid = nid;
		$fid = fid;
		layer.open({
			type: 2,
			title: '选择员工',
			area: ['700px', '530px'],
			fix: true, //不固定
			maxmin: true,
			content: url
		});
	}

	/**
	 * 删除充值卡数据
	 */
	function initSetState() {
		$('.table').on('click','.but_set_state', function(){
			var obj = $(this);
			var member_id = obj.attr('mid');
			var id = obj.attr('did');
			var url = obj.attr('durl');
			var info = '删除';


			layer.confirm(
				'确定要【' + info + '】此数据吗？',
				{
					icon: 3,
					title: '系统提示',
					btn: ['确 定', '取 消']
				},
				function(index){
					layer.close(index);
					layer.load();
					$.post(
						url,
						{id: id, member_id: member_id},
						function(data){
							if(data.status == 1) {
								layer.alert(msg, {icon: 1});

							} else {
								$.ajax({
									type:'POST',
									dataType:'json',
									url:'/business/financial/cashier?action=productlist',
									data:{member_id:member_id},
									success:function (data){

										if(data.state==1){
											var index = parent.layer.getFrameIndex(window.name);
											var html = '';
											function trans(data) {
												var $type;
												switch (data) {
													case '1':
														$type = '储值卡';
														break;
													case '2':
														$type = '疗程卡';
														break;
													case '3':
														$type = '家居产品';
														break;
													case '4':
														$type = '合作项目';
														break;
													case '5':
														$type = '服务项目';
														break;
												}
												return $type;
											}

											var arrSum = [];
											parent.$('.table tbody').empty();
											$.each(data.result,function(i,o){
												arrSum.push(o.really_price * o.count);
												html = '<tr dtype="'+o.finance_type+'">' +
													'<form>' +
													'<td>'+ trans(o.finance_type)+'<span>充值金额:'+ o.recharge+'</span><span>赠送金额:'+ o.give_balance+'</span></td>' +
													'<td>'+ o.consume_name+'</td>' +
													'<td>'+ o.sell_price+'</td>' +
													'<td><input class="calc reaPrice" type="text" value="'+o.really_price+'"/></td>' +
													'<td><input class="calc count" type="text" value="'+ o.count +'"></td>' +
													'<td>'+ o.really_price * o.count+'</td>' +
													'<td><a data-nid="'+i+'" class="add-member btn btn-sm" href="javascript:;" onclick="openP('+"'/business/financial/cashier?action=stafflist'"+','+ i +','+ o.finance_id+')">'+defaultVal(o.employee_name)+'</a></td>' +
													'<td><input class="saleFeat" type="text" value="'+ defaultReward(o.reward) +'"></td>' +
													'<td><input class="but_set_state btn btn-sm btn-borB " type="submit" value="删除" durl="/business/financial/cashier?action=delproduct" did="'+ o.finance_id+'" mid="'+ o.member_id+'"/></td>' +
													'</form>'+
													'</tr>';


												parent.$('.table tbody').append(html);


											});
											$('.table tr').each(function(){
												if($(this).attr('dtype') == 1) {
													$(this).find('span').show();
												} else {
													$(this).find('span').hide();
												}
											})
											var allMoney = arrSum.reduce(function (x,y) {
												return x + y;
											});
											parent.$('.table tbody').append('<tr style="border:none">' +
												'<td colspan="1" style="border-right: 0;">总计金额：' +
												'<em class="red">￥<span>'+allMoney+'</span></em>' +
												'</td>' +
												'<td class="text-right" colspan="8" style="border-left: 0;">' +
												'<em class="red">提示：</em>' +
												'会员有多次服务消费的情况，请选择疗程卡；会员单次项目服务消费的情况，请选择有服务项目会员消费后，无需提供后续服务，请选择无服务项目' +
												'</td>' +
												'</tr>');
											parent.$('.table').parent().find('.clearingBtn').removeClass('hide');
											parent.layer.close(index);

										}else{
											layer.alert(data.message, {icon: 5});
										}
									}
								})
								layer.closeAll();

							}
						},
						'json'
					);
				},
				function(index){
					layer.close(index);
				}
			);
		});
	}

	/**
	 * 结算单获取总金额
	 */
	var $tmoney;
	function getTotalMoney() {
		return $tmoney;
	}
	$('.clearingBtn').click(function(){
		$tmoney = ($('.total-money').text())
	})

	$(function(){
		window.formResult = formResult;
		window.select_user = select_user;
		window.getUserlist = getUserlist;
		window.closeWindow = closeWindow;
		window.getMember_id = getMember_id;
		window.getNid = getNid;
		window.getFid = getFid;
		window.openP = openP;
		window.getTotalMoney = getTotalMoney;
		window.defaultVal = defaultVal;
		window.defaultReward = defaultReward;
		initSetState();

		$(".table").on("change",".reaPrice",function(event){
			var $this = $(this);
			$this.each(function(){
				var r = /^-?\d+$/ ;
				var s = /^[0-9]+\.[0-9]{0,2}$/;
				if($(this).val() !=''&&!r.test($(this).val())&&!s.test($(this).val())){
					$(this).val("");
				} else {
					var id = $this.parent().parent().find('.but_set_state').attr('did'),
						member_id =  $this.parent().parent().find('.but_set_state').attr('mid'),
						really_price = $this.val();

					$.ajax({
						type:'POST',
						dataType:'json',
						url:'/business/financial/cashier?action=updateproduct',
						data:{id:id,member_id:member_id,really_price:really_price},
						success:function (data){
							if(data.state==0){
								layer.alert(data.message, {icon: 5});
							}else{
								$.ajax({
									type:'POST',
									dataType:'json',
									url:'/business/financial/cashier?action=productlist',
									data:{member_id:member_id},
									success:function (data){

										if(data.state==1){
											var html = '';
											function trans(data) {
												var $type;
												switch (data) {
													case '1':
														$type = '储值卡';
														break;
													case '2':
														$type = '疗程卡';
														break;
													case '3':
														$type = '家居产品';
														break;
													case '4':
														$type = '合作项目';
														break;
													case '5':
														$type = '服务项目';
														break;
												}
												return $type;
											}

											var arrSum = [];
											parent.$('.table tbody').empty();
											$.each(data.result,function(i,o){
												arrSum.push(o.really_price * o.count);
												html = '<tr>' +
													'<form>' +
													'<td class="types"><i>'+ trans(o.finance_type)+'</i><span>充值金额:'+ o.recharge+'</span><span>赠送金额:'+ o.give_balance+'</span></td>' +
													'<td>'+ o.consume_name+'</td>' +
													'<td>'+ o.sell_price+'</td>' +
													'<td><input class="calc reaPrice" type="text" value="'+o.really_price+'"/></td>' +
													'<td><input class="calc count" type="text" value="'+ o.count +'"></td>' +
													'<td>'+ o.really_price * o.count+'</td>' +
													'<td><a data-nid="'+i+'" class="add-member btn btn-sm" href="javascript:;" onclick="openP('+"'/business/financial/cashier?action=stafflist'"+','+ i +','+ o.finance_id+')">'+defaultVal(o.employee_name)+'</a></td>' +
													'<td><input class="saleFeat" type="text" value="'+ defaultReward(o.reward) +'"></td>' +
													'<td><input class="but_set_state btn btn-sm btn-borB " type="submit" value="删除" durl="/business/financial/cashier?action=delproduct" did="'+ o.finance_id+'" mid="'+ o.member_id+'"/></td>' +
													'</form>'+
													'</tr>';


												parent.$('.table tbody').append(html);


											});
											var allMoney = arrSum.reduce(function (x, y) {
												return x + y;
											});
											parent.$('.table .types').each(function(){
												if($(this).find('i').text() !=='储值卡'){
													$(this).find('span').hide();
												}
											});
											parent.$('.table tbody').append('<tr style="border: none">' +
												'<td colspan="1" style="border-right: 0;">总计金额：' +
												'<em class="red">￥<span class="total-money">'+allMoney+'</span></em>' +
												'</td>' +
												'<td class="text-right" colspan="8" style="border-left: 0;">' +
												'<em class="red">提示：</em>' +
												'会员有多次服务消费的情况，请选择疗程卡；会员单次项目服务消费的情况，请选择有服务项目会员消费后，无需提供后续服务，请选择无服务项目' +
												'</td>' +
												'</tr>');
											parent.$('.table').parent().find('.clearingBtn').removeClass('hide');



										}else{
											layer.alert(data.message, {icon: 5});
										}
									}
								})
							}
						}
					})
				}
			});



		});
		$(".table").on("change",".count",function(event){
			var $this = $(this);
			$this.each(function(){
				var r = /^-?\d+$/ ;
				if($(this).val() !=''&&!r.test($(this).val())){
					$(this).val("");
				} else {
					var id = $this.parent().parent().find('.but_set_state').attr('did'),
						member_id =  $this.parent().parent().find('.but_set_state').attr('mid'),
						count = $this.val();

					$.ajax({
						type:'POST',
						dataType:'json',
						url:'/business/financial/cashier?action=updateproduct',
						data:{id:id,member_id:member_id,count:count},
						success:function (data){
							if(data.state==0){
								layer.alert(data.message, {icon: 5});
							}else{
								$.ajax({
									type:'POST',
									dataType:'json',
									url:'/business/financial/cashier?action=productlist',
									data:{member_id:member_id},
									success:function (data){

										if(data.state==1){
											var html = '';
											function trans(data) {
												var $type;
												switch (data) {
													case '1':
														$type = '储值卡';
														break;
													case '2':
														$type = '疗程卡';
														break;
													case '3':
														$type = '家居产品';
														break;
													case '4':
														$type = '合作项目';
														break;
													case '5':
														$type = '服务项目';
														break;
												}
												return $type;
											}

											var arrSum = [];
											parent.$('.table tbody').empty();
											$.each(data.result,function(i,o){
												arrSum.push(o.really_price * o.count);
												html = '<tr>' +
													'<form>' +
													'<td class="types"><i>'+ trans(o.finance_type)+'</i><span>充值金额:'+ o.recharge+'</span><span>赠送金额:'+ o.give_balance+'</span></td>' +
													'<td>'+ o.consume_name+'</td>' +
													'<td>'+ o.sell_price+'</td>' +
													'<td><input class="calc reaPrice" type="text" value="'+o.really_price+'"/></td>' +
													'<td><input class="calc count" type="text" value="'+ o.count +'"></td>' +
													'<td>'+ o.really_price * o.count+'</td>' +
													'<td><a data-nid="'+i+'" class="add-member btn btn-sm" href="javascript:;" onclick="openP('+"'/business/financial/cashier?action=stafflist'"+','+ i +','+ o.finance_id+')">'+defaultVal(o.employee_name)+'</a></td>' +
													'<td><input class="saleFeat" type="text" value="'+ defaultReward(o.reward) +'"></td>' +
													'<td><input class="but_set_state btn btn-sm btn-borB" type="submit" value="删除" durl="/business/financial/cashier?action=delproduct" did="'+ o.finance_id+'" mid="'+ o.member_id+'"/></td>' +
													'</form>'+
													'</tr>';


												parent.$('.table tbody').append(html);


											});
											var allMoney = arrSum.reduce(function (x, y) {
												return x + y;
											});
											parent.$('.table .types').each(function(){
												if($(this).find('i').text() !=='储值卡'){
													$(this).find('span').hide();
												}
											});
											parent.$('.table tbody').append('<tr style="border: none">' +
												'<td colspan="1" style="border-right: 0;">总计金额：' +
												'<em class="red">￥<span class="total-money">'+allMoney+'</span></em>' +
												'</td>' +
												'<td class="text-right" colspan="8" style="border-left: 0;">' +
												'<em class="red">提示：</em>' +
												'会员有多次服务消费的情况，请选择疗程卡；会员单次项目服务消费的情况，请选择有服务项目会员消费后，无需提供后续服务，请选择无服务项目' +
												'</td>' +
												'</tr>');
											parent.$('.table').parent().find('.clearingBtn').removeClass('hide');

											parent.layer.close(index);

										}else{
											layer.alert(data.message, {icon: 5});
										}
									}
								})
							}
						}
					})
				}


			});

/*			var $money = $this.parent().parent().find('.reaPrice').val();
			var $count =  $this.parent().parent().find('.count').val();
			$this.parent().parent().find('.saleFeat').val($money * $count);*/

		})
		$(".table").on("change",".saleFeat",function(event){
			var $this = $(this);
			$this.each(function(){
				var r = /^-?\d+$/ ;
				var s = /^[0-9]+\.[0-9]{0,2}$/;
				if($(this).val() !=''&&!r.test($(this).val())&&!s.test($(this).val())){
					$(this).val("");
				} else {
					var id = $this.parent().parent().find('.but_set_state').attr('did'),
						member_id =  $this.parent().parent().find('.but_set_state').attr('mid'),
						reward = $this.val();

					$.ajax({
						type:'POST',
						dataType:'json',
						url:'/business/financial/cashier?action=updateproduct',
						data:{id:id,member_id:member_id,reward:reward},
						success:function (data){
							if(data.state==0){
								layer.alert(data.message, {icon: 5},function(){
									layer.closeAll();
									$this.val('');
								});
							}else{
								$.ajax({
									type:'POST',
									dataType:'json',
									url:'/business/financial/cashier?action=productlist',
									data:{member_id:member_id},
									success:function (data){

										if(data.state==1){
											var html = '';
											function trans(data) {
												var $type;
												switch (data) {
													case '1':
														$type = '储值卡';
														break;
													case '2':
														$type = '疗程卡';
														break;
													case '3':
														$type = '家居产品';
														break;
													case '4':
														$type = '合作项目';
														break;
													case '5':
														$type = '服务项目';
														break;
												}
												return $type;
											}

											var arrSum = [];
											parent.$('.table tbody').empty();
											$.each(data.result,function(i,o){
												arrSum.push(o.really_price * o.count);
												html = '<tr>' +
													'<form>' +
													'<td class="types"><i>'+ trans(o.finance_type)+'</i><span>充值金额:'+ o.recharge+'</span><span>赠送金额:'+ o.give_balance+'</span></td>' +
													'<td>'+ o.consume_name+'</td>' +
													'<td>'+ o.sell_price+'</td>' +
													'<td><input class="calc reaPrice" type="text" value="'+o.really_price+'"/></td>' +
													'<td><input class="calc count" type="text" value="'+ o.count +'"></td>' +
													'<td>'+ o.really_price * o.count+'</td>' +
													'<td><a data-nid="'+i+'" class="add-member btn btn-sm" href="javascript:;" onclick="openP('+"'/business/financial/cashier?action=stafflist'"+','+ i +','+ o.finance_id+')">'+defaultVal(o.employee_name)+'</a></td>' +
													'<td><input class="saleFeat" type="text" value="'+ defaultReward(o.reward) +'"></td>' +
													'<td><input class="but_set_state btn btn-sm btn-borB " type="submit" value="删除" durl="/business/financial/cashier?action=delproduct" did="'+ o.finance_id+'" mid="'+ o.member_id+'"/></td>' +
													'</form>'+
													'</tr>';


												parent.$('.table tbody').append(html);


											});
											var allMoney = arrSum.reduce(function (x, y) {
												return x + y;
											});
											parent.$('.table .types').each(function(){
												if($(this).find('i').text() !=='储值卡'){
													$(this).find('span').hide();
												}
											});
											parent.$('.table tbody').append('<tr style="border: none">' +
												'<td colspan="1" style="border-right: 0;">总计金额：' +
												'<em class="red">￥<span class="total-money">'+allMoney+'</span></em>' +
												'</td>' +
												'<td class="text-right" colspan="8" style="border-left: 0;">' +
												'<em class="red">提示：</em>' +
												'会员有多次服务消费的情况，请选择疗程卡；会员单次项目服务消费的情况，请选择有服务项目会员消费后，无需提供后续服务，请选择无服务项目' +
												'</td>' +
												'</tr>');
											parent.$('.table').parent().find('.clearingBtn').removeClass('hide');

											parent.layer.close(index);

										}else{
											layer.alert(data.message, {icon: 5});
										}
									}
								})
							}
						}
					})
				}
			});
		});
		$(".add").click(function(){
			layer.open({
			    type: 2,
			    area: ['1000px', '640px'],
			    title:$(this).attr('dtitle'),
			    fix: true, //不固定
			    maxmin: true,
			    content: $(this).attr('durl')
			});
		})  
		$(".card_add").click(function(){
			layer.open({
				type: 2,
				area: ['623px','343px'],
				title:$(this).attr('dtitle'),
				fix: true, //不固定
				maxmin: true,
				content: $(this).attr('durl')
			});
		})
		$(".price_add").click(function(){
			layer.open({
				type: 2,
				area: ['520px','340px'],
				title:$(this).attr('dtitle'),
				fix: true, //不固定
				maxmin: true,
				content: $(this).attr('durl')
			});
		})
		$(".clear_add").click(function(){
			layer.open({
				type: 2,
				area: ['620px','410px'],
				title:$(this).attr('dtitle'),
				fix: true, //不固定
				maxmin: true,
				content: $(this).attr('durl')
			});
		})


	});
})(jQuery)



